<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use think\facade\Cache;
use Lcobucci\JWT\Parser;

// Config配置
const CREATE_TABLE_AMOUNT = 'create_table_amount'; // 创建牌桌金额

// RedisKey配置
const REDIS_TABLE = 'redis_table_'; // 牌桌配置
const REDIS_TABLE_JOIN = 'redis_table_join_'; // 加入牌桌配置
const REDIS_USER_TABLE = 'redis_user_table_'; // 用户进入的牌桌
const REDIS_LICENSING_POKER = 'redis_licensing_poker_'; // 梭哈发牌
const REDIS_PLAYER_HAND = 'redis_player_hand_'; // 玩家手牌
const REDIS_GOOD_CARDS = 'redis_good_gards_';   // 好牌玩家
const REDIS_CALL_CARDS = 'redis_call_cards_';   // 叫牌

// 常量配置
const ADMIN_LOCK_COUNT = 'admin_lock_count';    // 后台登录错误锁
const IP_LOCK_COUNT = 'ip_lock_count';          // 用户ip锁
const SMS_CODE_LOCK = 'sms_code_lock';          // 验证码锁
const USER_LOGIN_LOCK = 'user_login_lock';      // 用户登录锁

// 订单类型
const ORDER_TYPE_RECHARGE   = 'RE';    // 充值
const ORDER_TYPE_WITHDRAWAL = 'WR';    // 提现管理
const ORDER_TYPE_BETWIN  = 'OBW';      // 投注赢
const ORDER_TYPE_BETLOSE = 'OBL';      // 投注输
const ORDER_TYPE_BETBACE = 'OBC';      // 投注输-退剩余

/**
 * 返回结果
 * @param  [type] $msg        信息
 * @param  [type] $data       数据
 * @param  [type] $permission 认证
 * @return [type]             [description]
 */
function result($msg, $data, $permission)
{
    return [
        'msg'   => $msg,
        'data'  => $data,
        'permission' => $permission
    ];
}

/**
 * 后台访问时 获取客户IP
 * @return string
 */
function get_ip()
{
    if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR']) {
        $ip = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : '127.0.0.1';
    }elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']) {
        $ip = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
        $ip = trim($ip[0]);
        $ip = $ip ? $ip : '127.0.0.1';
    }else{
        $ip = '127.0.0.1';
    }
    return $ip;
}

/**
 * post请求
 * @param  [type] $url  [description]
 * @param  [type] $data [description]
 * @return [type]       [description]
 */
function fetch_post($url, $data)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

    // 忽略证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    curl_close($ch);

    return $output;
}

/**
 * get请求
 * @param  [type] $url  [description]
 * @return [type]       [description]
 */
function fetch_get($url)
{
    $ch = curl_init();

    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    // 忽略证书
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $output = curl_exec($ch);
    curl_close($ch);

    return $output;
}

/**
 * JWT加密
 * @param  [type] $data array需要加密的字符串, 必须包含ID
 * @return [type]         [description]
 */
function buildJwt($data)
{
    $key = 'jwt_'.$data['id'];
    $jwt_sign = Cache::get($key);
    if (!empty($jwt_sign)) {
        return $jwt_sign;
    }

    $builder = new Builder();
    $signer  = new Sha256();

    $builder->setIssuer(config()['app']['app_name']);
    $builder->setAudience(config()['app']['app_name']);
    $builder->setIssuedAt(time());
    $builder->setNotBefore(time() + 60);
    $builder->setExpiration(time() + 3600 * 24 * 7);
    $builder->set('data', json_encode($data));
    $builder->sign($signer, '__TOKEN_SIGN_KEY__');
    $token = (string)$builder->getToken();

    Cache::set($key, $token, 3600 * 24 * 7);
    return $token;
}

/**
 * 验证JWT
 * @param  [type] $string 需要解密验证的字符串
 * @param  [type] $token  [description]
 * @return [type]         [description]
 */
function verifyJwt($data, $token)
{
    $key = 'jwt_'.$data['id'];
    $jwt_sign = Cache::get($key);

    if (empty($jwt_sign) || $token != $jwt_sign) {
        return false;
    }

    return true;
}

/**
 * 解开JWT
 *
 * @return [type] [description]
 */
function solveJwt($token)
{
    if (empty($token)) {
        return false;
    }

    $parse = (new Parser())->parse($token);
    $data  = json_decode($parse->getClaim('data'), true);
    $key = 'jwt_'.$data['id'];
    if (empty($data)) {
        return false;
    }

    return $data;
}

/**
 * 分页条数选项
 * @param  [type] $limit 每页多少条
 * @return [type]        [description]
 */
function select_limit($limit)
{
    $count = 5;
    $option = '';
    for ($i = 1; $i <= $count; $i++) {
        if ($limit == $i*10) {
            $option .= "<option selected value='".($i*10)."'>".($i*10)."条/页</option>";
        } else {
            $option .= "<option value='".($i*10)."'>".($i*10)."条/页</option>";;
        }
    }

    $html  = '<select onchange="selectlimit()" class="select-page" name="limit">';
    $html .= $option;
    $html .= '</select>';

    return $html;
}
